var express = require('express');
var router = express.Router();
var indexController = require('../controllers/index.js');
/* GET home page. */
router.get('/', indexController.getIndex);


var models = require("../models")

var Collections = models.collections
var Resmocks = models.resmocks

var Mock = require("mockjs")

router.all('/m/**', function (req, res) {

    console.log(req.path)
    console.log(req.path.split('/'))

    let parray = req.path.split('/')
    let collpath = parray[2]
    parray.shift()
    parray.shift()
    parray.shift()
    let mockurl = parray.join('/')
    let method = req.method;

    mockurl='/'+mockurl
    
    console.log("requestMethod=",method)
    console.log("collpath=",collpath)
    console.log("mockurl=",mockurl)


    // 找到 collection
    Collections.findOne({
        where: {
            path: collpath
        }
    }).then((data)=>{
        if(data){
            // 找到所有的mocks
            Resmocks.findAll({
                where:{
                    collect:data.name
                }
            }).then((dlist)=>{
                if(dlist){

                    // console.debug(JSON.stringify(dlist))

                    let candidate = null
                    let length = 0
                    dlist.forEach((it1, index)=>{
                        let {url, meth, fcode} = it1
                        if(mockurl.startsWith(url) && url.length>length){
                            if(method=='ALL' || method == meth){
                                 candidate = it1
                            }
                        }
                    })

                    if(candidate){
                        console.log("SUCCESS  ---- fund candait", collpath, mockurl)
                        // console.log(JSON.stringify(candidate))

                        try{

                            let result = eval('('+ candidate.fcode +')')
                            res.json(result)
                            res.end()
                            console.log("mock success -------------------")

                        }catch(e){
                            console.log("Eval error", candidate.fcode)
                            res.status(400).send("FCODE EVAL ERROR")

                        }

                    }else{
                        console.warn("no cadidate", collpath, mockurl)
                        notfount(req,res)
                    }

                }else{
                    // dlist is null
                    console.log("dlist", dlist)
                    notfount(req, res)
                }


            }).catch(e=>{
                console.error("findAll mocks error", e)
                notfount(req, res)
            })

        }else{

            // collecion is null
            console.warn("there is no collecion", collpath)
            notfount(req, res)
        }

    }).catch( (err)=>{
        // collecions ERROR
        console.log("findOne Collection", err)
        notfount(req,res)
    })

})

function notfount(req, res){
    res.status(400)
    res.end("not find match mock for url:"+req.path)
}


router.get("/collections/:id", function(req, res){
    let id=req.params.id
    Collections.findOne({
        while:{
            id:id
        }
    }).then(function(data){
        let rdata = {}
        Object.assign(rdata, data);
        res.json(rdata);
        res.end()
    }).catch(e=>{
        console.error("get collections:id error", e)
        res.status(400)
        res.end
    })
})

/**
 *  返回collection列表
 */
router.get("/collections", function (req, res) {
    Collections.findAll().then(function (data) {
        res.json(data)
        res.end()
    }).catch(function (err) {
        console.log("get collections error:", e)
        res.status(400)
        res.end()
    })
})

/**
 *  更新,新增 collections   body param json {name: , path: , descrip}
 */
router.put("/collections", function (req, res) {
    let name1 = req.body.name
    Collections.findOne({
        where: {
            name: name1
        }
    }).then(function (data) {
        if (data) {

            delete req.body.id
            Collections.update(req.body, {
                where: {
                    name: name1
                }
            }).then(function (ndata) {
                console.log("update collecions :", ndata)
                res.status(200)
                res.json({ code: 0, message: "updated" })
                res.end()
            }).catch(e => {
                console.log("update collecions error:", e)
                res.status(400)
                res.end()
            })

        } else {
            delete req.body.id
            Collections.create(req.body).then(function (data) {
                console.log("create collection:", data)
                res.status(201)
                res.json({ code: 0, message: "created" })
                res.end()
            }).catch(e => {
                console.log("create collecions error:", e)
                res.status(400)
                res.end()
            })
        }
    }).catch((e) => {
        console.log("put connections error:", e)
        res.status(400)
        res.end()
    })
})

/**
 *  删除
 */
router.delete("/collections/:id", function (req, res) {
    let id = req.params.id
    Collections.destroy({
        where: {
            id: id
        }
    }).then((data) => {
        console.log("delete collections :", id, data)
        res.status(200)
        res.json({ code: 0, message: "delete" })
        res.end()
    }).catch(e => {
        console.log("delete collection error:", e)
        res.status(400)
        res.end()
    })
})

/**
 * 
 *  获取collection 下面的所有mocks
 */
router.get("/resmocks/:coll", function (req, res) {
    let coll = req.params.coll
    console.log("coll", coll)
    Resmocks.findAll({
        where:{
            collect:coll
        }
    }).then((data)=> {
        // console.log("/resmocks", data)
        res.json(data)
        res.end()
    }).catch(function(e) {
        res.status(400)
        res.end()
    })
})

/**
 * 更新 新增 resmocks
 */
router.put("/resmocks", function (req, res) {
    let coll = req.body.collect
    let name = req.body.name
    let id = req.body.id
    if (id != undefined && id != '' && id != null) {
        Resmocks.update(req.body, {
            where: {
                id: id
            }
        }).then(data => {
            res.status(200)
            res.json({ code: 0, message: "updated" })
            res.end()
        }).catch(e => {
            console.log("resmock update failed", e)
            res.status(400)
            res.end()
        })

    } else {
        Resmocks.create(req.body).then(data=>{
            res.status(200)
            res.json({ code: 0, message: "created" })
            res.end()
        }).catch(e => {
            console.log("resmock created failed", e)
            res.status(400)
            res.end()
        })
    }
})

/**
 * 删除
 */
router.delete("/resmocks/:id",function(req, res){
    let ids = req.params.id
    console.log("delete id",ids)
    Resmocks.destroy({
        where:{
            id:ids
        }
    }).then(data=>{
        console.log("delete resmocks id:", ids)
        res.status(200)
        res.json({code:0, message:'delete'})
        res.end()
    }).catch(e=>{
        console.error("delete resmcks error", ids, e)
        res.status(400)
        res.send("DB Oper Failed")
        res.end()
    })


})

module.exports = router;
